<?php

declare(strict_types=1);


namespace App\CustHub\Controller;

use App\Common\Constants\ErrorCode;
use App\Common\Helpers\SortHelper;
use App\CustHub\Annotation\ApiAuth;
use App\CustHub\Annotation\ChPermission;
use App\CustHub\Annotation\VerifySignature;
use App\CustHub\Constants\CrowSendingConstants;
use App\CustHub\Constants\SendConfigConstants;
use App\CustHub\Model\ChCrowdInvite;
use App\CustHub\Model\ChCrowdInviteLog;

use App\CustHub\Model\ChCrowdInviteSubTask;

use App\CustHub\Request\RoomKeywordRequest;
use App\CustHub\Service\ChContactService;
use App\CustHub\Service\ChSendConfigService;
use App\CustHub\Service\CrowdInviteService;

use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\Di\Annotation\Inject;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;

#[Controller(prefix: 'ch/crowd_invite'),ApiAuth,VerifySignature]
class CrowdInviteController extends BaseController
{

    #[Inject]
    protected CrowdInviteService $service;

    #[Inject]
    protected ChContactService $contactService;

    #[Inject]
    protected ChSendConfigService $sendService;

    public array $noNeedLogin = ['export'];
    public array $noNeedVerifySign = ['export'];

    /**
     * 邀请用户
     */
    public function invite()
    {
        $this -> validateParam([
            'contact_id' => 'required',
            'corp_id' => 'required',
            'contact_type' => 'required',
            'is_guide' => 'required',
        ]);
        $contact_id =$this->request->input('contact_id');
        $mainUid = $this->request->input('main_uid');

    }

    /**
     * 添加
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('add'),ChPermission('ch:crowd_invite:add')]
    public function addInvite()
    {
        $this -> validateParam([
            'title' => 'required',
            'corp_id' => 'required',
            'contact_type' => 'required',
            'is_guide' => 'required',
            'send_times' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $params = $this -> request -> all();
        $res = $this -> service -> saveIvnite($uid,$mainUid,$params);
        return $this -> success('添加成功',$res);
    }


    #[PostMapping('edit'),ChPermission('ch:crowd_invite:edit')]
    public function editInvite()
    {
        $this -> validateParam([
            'title' => 'required',
            'corp_id' => 'required',
            'contact_type' => 'required',
            'is_guide' => 'required',
            'id' => 'required',
            'send_times' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $id =$this->request->input('id');
        $mainUid = $this->request->input('main_uid');
        $params = $this -> request -> all();
        $res = $this -> service -> saveIvnite($uid,$mainUid,$params,$id);
        return $this -> success('修改成功',$res);
    }


    #[PostMapping('delete'),ChPermission('ch:crowd_invite:delete')]
    public function delete()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $id =$this->request->input('id');
        $mainUid = $this->request->input('main_uid');
        $params = $this -> request -> all();
        $res = ChCrowdInvite::query() -> where('id',$id) -> delete();
        if($res){
            return $this -> success('删除成功');
        }
        return $this -> success('删除失败');

    }

    #[PostMapping('detail'),ChPermission('ch:crowd_invite:detail')]
    public function detail()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');
        $info = ChCrowdInvite::query() -> with(['user' => function ($q) {
            $q->select('id', 'nickname');
        }]) -> where('id',$id) -> first() -> toArray();
        if(!empty($info['contact_ids'])){
            $contactInfo=getContactIds($info['contact_ids']);
            var_dump($contactInfo);
            $info['contact_ids_array'] = $this -> contactService -> getContactByUserIds($contactInfo['contacts']);
        }
        !empty($info['condition']) && $info['condition'] = $this -> service -> formatCondition( $info['condition']);
        //获取下发微信列表
        $robotList = ChCrowdInviteSubTask::query() -> with(['robot' => function($q){
            $q -> select(['id','nickname','avatar','user_id','login_status','corp_name']);
        }])-> where('invite_id',$info['id']) -> select(['id','robot_id','custom_total','complete_total']) -> get();
        $info['robot_list'] = $robotList;
        return $this -> success('获取成功',$info);
    }

    #[PostMapping('record'),ChPermission('ch:crowd_invite:record')]
    public function record()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        $params = $this -> request -> all();
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $page_size = $this->request->input('page_size');
        if (!empty($params['status']) || $params['status'] === 0 || $params['status'] === "0") {
            $where[] = ['status', $params['status']];
        }
        //$page_size =$this->request->input('page_size',15);
        $id = $this->request->input('id');
        $records = ChCrowdInviteLog::query() -> with(['contact'=>function($q){
            $q -> select(['nickname','user_id','type','avatar','is_wechat','corp_short_name']);
        },'room' => function($q){
            $q -> select(['room_name','room_wxid','customer_room_type','room_avatar_url']);
        }]) -> where('sub_id',$id)  -> where($where) -> paginate((int)$page_size);
        $subTask=ChCrowdInviteSubTask::query()->where('id',$id)->first();
        $total = $records -> total();
        $complete_total = $subTask -> complete_total;
        $suplus_total = $subTask -> custom_total-$complete_total;
        $data = [
            'items' => $records -> items(),
            'suplus_total'=>$suplus_total,
            'complete_total'=>$complete_total,
            'pageInfo' => [
                'total' => $records->total(),
                'currentPage' => $records->currentPage(),
                'totalPage' => $records->lastPage(),
            ],
        ];
        return $this -> success('获取成功',$data);
    }

    #[PostMapping('list'),ChPermission('ch:crowd_invite:list')]
    public function List()
    {
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $page_size =$this->request->input('page_size',15);
        $params = $this -> request -> all();

        $where = [];
        $where[] = ['main_uid',$mainUid];
        if (!empty($params['keyword'])) {
             $where[] = ['title', 'like', "%" . $params['keyword'] . "%"];
        }
        if (!empty($params['status']) || $params['status'] === 0 || $params['status'] === "0") {
            $where[] = ['status', $params['status']];
        }
        if (!empty($params['account_id'])) {
            $where[] = ['uid', $params['account_id']];
        }
        $page = ChCrowdInvite::query() -> with(['user' => function ($q) {
            $q->select('id', 'nickname');
        }]) -> where($where) -> orderBy('id','desc')->paginate((int)$page_size);
        $list = $page -> items();
        //todo 子任务拉群
//        foreach ($list as &$item){
//            //$item -> task_total = 0;
//            //$item -> complate_total = 0;
//            //!empty($item -> contact_ids) && $item -> contact_ids_array = $this -> contactService -> getContactByUserIds($item -> contact_ids);
//            //!empty($item -> condition) && $item -> condition = $this -> service -> formatCondition($item -> condition);
//        }
        $total = $page -> total();
        return $this -> success('获取成功',['list'=>$list,'total'=>$total]);
    }

    #[PostMapping('cancel'),ChPermission('ch:crowd_invite:cancel')]
    public function cancel()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');
        $res = ChCrowdInvite::query() -> where('id',$id) -> update(['status'=>CrowSendingConstants::CANCEL]);
        return $this -> success('操作成功');
    }


    #[PostMapping('start'),ChPermission('ch:crowd_invite:start')]
    public function start()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');
        $res = ChCrowdInvite::query() -> where('id',$id) -> update(['status'=>CrowSendingConstants::WAIT_SEND]);
        return $this -> success('操作成功');
    }

    #[PostMapping('pause'),ChPermission('ch:crowd_invite:pause')]
    public function pause()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');
        $res = ChCrowdInvite::query() -> where('id',$id) -> update(['status'=>CrowSendingConstants::PAUSE]);
        return $this -> success('操作成功');
    }


    #[PostMapping('system/list'), ChPermission('ch:crowd:crowd_invite:system:list')]
    public function systemList()
    {
        $data = $this->request->all();
        $data['type'] = SendConfigConstants::BRANCH_INVITE;
        $list = $this->sendService->getConfigList($data);
        return $this->success('获取成功', $list);
    }


    #[PostMapping('system/detail'), ChPermission('ch:crowd:crowd_invite:system:detail')]
    public function systemDetail()
    {
        $this->validateParam([
            'robot_id' => 'required',
        ]);

        $mainUid = $this->request->input('main_uid');
        $uid = $this->request->input('uid');
        $robot_id = $this->request->input('robot_id');
        $detail = $this->sendService->getConfig(SendConfigConstants::BRANCH_INVITE, $uid, $robot_id);
        return $this->success('获取成功', $detail);
    }

    #[PostMapping('system/save'), ChPermission('ch:crowd_invite:sending:system:save')]
    public function saveSystem()
    {
        $this->validateParam([
            'robot_ids' => 'required',
            'value' => 'required',
        ]);
        $mainUid = $this->request->input('main_uid');
        $uid = $this->request->input('uid');
        $type = $this->request->input('type');
        $corp_id = $this->request->input('corp_id');
        $robot_ids = $this->request->input('robot_ids');
        $value = $this->request->input('value');
        $robot_ids = !is_array($robot_ids) ? json_decode($robot_ids, true) : $robot_ids;
        foreach ($robot_ids as $robot_id) {
            $this->sendService->saveConfig(SendConfigConstants::BRANCH_INVITE, $uid, $mainUid, $corp_id, $robot_id, $value);
        }
        return $this->success('保存成功', []);
    }


    #[PostMapping('statistics'), ChPermission('ch:crowd_invite:statistics')]
    public function statistics()
    {
        $this->validateParam([
            'type' => 'required',
        ]);
        $data=$this->service->statistices($this->request->all());
        return $this->success('获取成功', $data);
    }

    #[GetMapping('statistics/export')]
    public function export(): \Psr\Http\Message\ResponseInterface
    {
        return $this->service->exportStatistics($this->request->all());
    }

    /**
     * 获取生效群列表
     * @param RoomKeywordRequest $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    #[PostMapping('active_rooms')]
    public function getActiveRooms()
    {
        return $this->success($this->service->getActiveRoomPageList($this -> request->all()));
    }



    /**
     * 设置进粉状态
     */
    #[PostMapping('set_active_room_status')]
    public function setActiveRoomStatus()
    {
        return $this->service->setActiveRoomStatus($this->request->all()) ? $this->success() : $this->error();
    }

}